package com.gxa.ehome.web.servlet;

import com.alibaba.fastjson.JSON;
import com.gxa.ehome.entity.Admin;
import com.gxa.ehome.exception.BusinessException;
import com.gxa.ehome.service.AdminService;
import com.gxa.ehome.service.impl.AdminServiceImpl;
import com.gxa.ehome.util.JsonResult;
import com.gxa.ehome.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "AdminServlet",urlPatterns = "/admin")
public class AdminServlet extends HttpServlet {
    private AdminService adminService=new AdminServiceImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理请求中的中文, 使用UTF-8编码
        request.setCharacterEncoding("UTF-8");
//        String code=null;
//        String msg=null;
//        String data = "{}";
        JsonResult jsonResult = new JsonResult();
        String method = request.getHeader("method");
        switch (method) {
            case "login": {
                String phone= request.getParameter("phone");
                String pwd= request.getParameter("pwd");
                System.out.println(phone);
                Admin loAdmin=null;
                try {
                    loAdmin = adminService.login(phone, pwd);
//                    System.out.println(loAdmin);
                    if (loAdmin!=null){
                        jsonResult.setCode("1");
                        jsonResult.setMsg("登录成功,欢迎回来,"+loAdmin.getName());
                    }else {
                        jsonResult.setCode("0");
                        jsonResult.setMsg("登录失败");
                    }
                } catch (Exception e) {
                    jsonResult.setCode("0");
                    if(e instanceof BusinessException){
                        jsonResult.setMsg(e.getMessage());
                    }else{
                        e.printStackTrace();   // 将来要改为记录日志操作
                    }
                }
                break;
            }
            default:{
                break;}
        }
        response.setCharacterEncoding("UTF-8");   // 服务器端的字符集设置(影响流)- java代码相关
        response.setHeader("Content-Type", "text/html;charset=UTF-8"); // 浏览器行为
//        PrintWriter writer = response.getWriter();
//
//        String s = JSON.toJSONString(jsonResult);
//        writer.print(s);
//        writer.flush();
//        writer.close();
        ResponseUtil.send(response,JSON.toJSONString(jsonResult.getValues()));

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
